package server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;

import utils.Hashes;
import utils.PrintMsg;
import utils.ServerMessage;

import common.Message;

public class ServerUDPSend implements Runnable
{
	final int ByteBufferLength = 2048;
	public static Queue<Message> UDPSendBuffer;
	public static Map<Long, Message> UDPACKBuffer;


	public ServerUDPSend()
	{
		UDPACKBuffer = new HashMap<Long,Message>();
		UDPSendBuffer = new LinkedList<Message>();
	}
	public  void run()
	{
		try
		{
			while (true)
			{
				synchronized(UDPSendBuffer)
				{
					while (UDPSendBuffer.size() > 0)
					{			
						int port = 9090;
						Message m = UDPSendBuffer.remove();
						ServerMessage sm = new ServerMessage(m.getData());
						
						m.setSendTime(System.currentTimeMillis());
						
						if(!sm.IsServerAck())
						{
							UDPACKBuffer.put(Hashes.CheckSum(m.getData()), m);
						}
							InetAddress Address = InetAddress.getByName(m.getDest().getIp());
							if(InetAddress.getLocalHost().getHostAddress().equals(Address.getHostAddress()))
							{
								break;
							}
							byte[] message = m.getData();
							
							// Initialize a datagram packet with data and address
							DatagramPacket packet = new DatagramPacket(message,
									message.length, Address, port);
							DatagramSocket dsocket = new DatagramSocket();
	
							PrintMsg.PrintStatic("Sending UDP Packet", "IP Address: " +  m.getDest().getIp() + "\n Message: "+ new String(message,0,message.length)+ "\n");
	
							dsocket.send(packet);
							dsocket.close();
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			
		}
	}

}
